import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import type { RouteRecordRaw } from 'vue-router'

// 路由配置
const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: () => import('@/components/Layout/MainLayout.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue')
      },
      {
        path: '/dashboard',
        redirect: '/'
      },
      {
        path: '/projects',
        name: 'Projects',
        component: () => import('@/views/ProjectList.vue')
      },
      {
        path: '/projects/create',
        name: 'CreateProject',
        component: () => import('@/views/CreateProject.vue')
      },
      {
        path: '/projects/:id',
        name: 'ProjectDetail',
        component: () => import('@/views/ProjectDetail.vue')
      },
      {
        path: '/projects/:id/edit',
        name: 'EditProject',
        component: () => import('@/views/EditProject.vue')
      },
      {
        path: '/tasks',
        name: 'Tasks',
        component: () => import('@/views/TaskList.vue')
      },
      {
        path: '/tasks/:id',
        name: 'TaskDetail',
        component: () => import('@/views/TaskDetail.vue')
      },
      {
        path: '/tasks/:id/edit',
        name: 'EditTask',
        component: () => import('@/views/EditTask.vue')
      },
      {
        path: '/tasks/:id/assign',
        name: 'AssignTask',
        component: () => import('@/views/AssignTask.vue')
      },
      {
        path: '/issues',
        name: 'Issues',
        component: () => import('@/views/IssueList.vue')
      },
      {
        path: '/issues/create',
        name: 'CreateIssue',
        component: () => import('@/views/CreateIssue.vue')
      },
      {
        path: '/issues/my',
        name: 'MyIssues',
        component: () => import('@/views/MyIssues.vue')
      },
      {
        path: '/issues/:id',
        name: 'IssueDetail',
        component: () => import('@/views/IssueDetail.vue')
      },
      {
        path: '/issues/:id/edit',
        name: 'EditIssue',
        component: () => import('@/views/EditIssue.vue')
      },
      {
        path: '/issues/:id/assign',
        name: 'AssignIssue',
        component: () => import('@/views/AssignIssue.vue')
      },
      {
        path: '/reports',
        name: 'Reports',
        component: () => import('@/views/ReportList.vue')
      },
      {
        path: '/reports/create',
        name: 'CreateReport',
        component: () => import('@/views/CreateReport.vue')
      },
      {
        path: '/reports/:id',
        name: 'ReportDetail',
        component: () => import('@/views/ReportDetail.vue')
      },
      {
        path: '/reports/:id/edit',
        name: 'EditReport',
        component: () => import('@/views/EditReport.vue')
      },
      {
        path: '/users',
        name: 'Users',
        component: () => import('@/views/UserManagement.vue'),
        meta: { requiresAdmin: true }
      },
      {
        path: '/analytics',
        name: 'Analytics',
        component: () => import('@/views/Analytics.vue')
      },
      {
        path: '/profile',
        name: 'Profile',
        component: () => import('@/views/Profile.vue')
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/NotFound.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, _from, next) => {
  const authStore = useAuthStore()
  
  // 检查是否需要认证
  if (to.meta.requiresAuth !== false) {
    // 如果没有token，重定向到登录页
    if (!authStore.token) {
      next({ name: 'Login', query: { redirect: to.fullPath } })
      return
    }
    
    // 如果有token但没有用户信息，尝试获取用户信息
    if (!authStore.user) {
      try {
        await authStore.getCurrentUser()
      } catch (error) {
        // 获取用户信息失败，清除token并重定向到登录页
        authStore.logout()
        next({ name: 'Login', query: { redirect: to.fullPath } })
        return
      }
    }
    
    // 检查是否需要管理员权限
    if (to.meta.requiresAdmin && authStore.user?.role !== 'admin') {
      next({ name: 'Dashboard' })
      return
    }
  }
  
  // 如果已登录用户访问登录或注册页，重定向到首页
  if ((to.name === 'Login' || to.name === 'Register') && authStore.token) {
    next({ name: 'Dashboard' })
    return
  }
  
  next()
})

export default router